import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { prisma } from '@/lib/prisma';
import { redirect } from 'next/navigation';
import Link from 'next/link';
import { SignOutButton } from '@/app/components/SignOutButton';
import type { UserWithDetails } from '@/app/types';
import { unstable_noStore as noStore } from 'next/cache';

export default async function ProfilePage() {
  // 禁用缓存
  noStore();
  
  const session = await getServerSession(authOptions);
  
  if (!session?.user) {
    redirect('/api/auth/signin');
  }

  // 分别查询用户的行程和目的地数据
  const userTrips = await prisma.trip.findMany({
    where: {
      userId: session.user.id,
      isOfficial: false
    },
    orderBy: {
      createdAt: 'desc'
    },
    include: {
      _count: {
        select: {
          activities: true,
          savedBy: true,
          comments: true
        }
      }
    },
    take: 6
  });

  const userDestinations = await prisma.destination.findMany({
    where: {
      createdById: session.user.id,
      isOfficial: false
    },
    orderBy: {
      createdAt: 'desc'
    },
    include: {
      _count: {
        select: {
          activities: true
        }
      }
    },
    take: 3
  });

  const savedDestinations = await prisma.destination.findMany({
    where: {
      savedBy: {
        some: {
          id: session.user.id
        }
      }
    },
    include: {
      _count: {
        select: {
          activities: true
        }
      }
    },
    take: 6
  });

  // 查询用户收藏的行程
  const savedTrips = await prisma.trip.findMany({
    where: {
      savedBy: {
        some: {
          userId: session.user.id
        }
      }
    },
    include: {
      activities: true,
      user: {
        select: {
          id: true,
          name: true,
          username: true
        }
      },
      _count: {
        select: {
          activities: true,
          savedBy: true,
          comments: true
        }
      }
    },
    take: 6
  });

  // 获取收藏的行程总数
  const savedTripsCount = await prisma.savedTrip.count({
    where: {
      userId: session.user.id
    }
  });

  // 获取收藏的目的地总数
  const savedDestinationsCount = await prisma.destination.count({
    where: {
      savedBy: {
        some: {
          id: session.user.id
        }
      }
    }
  });

  return (
    <div className="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div className="bg-gray-800 rounded-lg shadow-lg overflow-hidden">
        {/* 用户信息部分 */}
        <div className="p-6">
          <div className="flex justify-between items-center">
            <h1 className="text-2xl font-bold text-white">
              {session.user.name || session.user.username}
            </h1>
            <SignOutButton />
          </div>
        </div>

        {/* 我的行程部分 */}
        <div className="border-t border-gray-700 p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-white">我的行程</h2>
            <Link
              href="/trips/new"
              className="text-blue-400 hover:text-blue-300 text-sm"
            >
              创建行程
            </Link>
          </div>
          {userTrips.length > 0 ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {userTrips.map((trip) => (
                <Link
                  key={trip.id}
                  href={`/trips/${trip.id}`}
                  className="block bg-gray-700 rounded-lg p-4 hover:bg-gray-600 transition"
                >
                  <h3 className="font-semibold text-white">{trip.title}</h3>
                  <p className="text-gray-300 text-sm mt-2">
                    {trip.description || '暂无描述'}
                  </p>
                  <div className="mt-4 flex items-center text-sm text-gray-400">
                    <span>{trip._count.activities} 个活动</span>
                    <span className="mx-2">•</span>
                    <span>{trip._count.savedBy} 人收藏</span>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <p className="text-gray-400">还没有创建任何行程</p>
          )}
        </div>

        {/* 我的目的地部分 */}
        <div className="border-t border-gray-700 p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-white">我的目的地</h2>
            <Link
              href="/destinations/new"
              className="text-blue-400 hover:text-blue-300 text-sm"
            >
              创建目的地
            </Link>
          </div>
          {userDestinations.length > 0 ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {userDestinations.map((destination) => (
                <Link
                  key={destination.id}
                  href={`/destinations/${destination.id}`}
                  className="block bg-gray-700 rounded-lg p-4 hover:bg-gray-600 transition"
                >
                  {destination.imageUrl && (
                    <div className="relative h-32 mb-4">
                      <img
                        src={destination.imageUrl}
                        alt={destination.name}
                        className="w-full h-full object-cover rounded"
                      />
                    </div>
                  )}
                  <h3 className="font-semibold text-white">{destination.name}</h3>
                  <p className="text-gray-300 text-sm mt-2">
                    {destination.description || '暂无描述'}
                  </p>
                </Link>
              ))}
            </div>
          ) : (
            <p className="text-gray-400">还没有创建任何目的地</p>
          )}
        </div>

        {/* 收藏的目的地部分 */}
        <div className="border-t border-gray-700 p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-white">收藏的目的地</h2>
            {savedDestinationsCount > 6 && (
              <Link
                href="/saved-destinations"
                className="text-blue-400 hover:text-blue-300 text-sm"
              >
                查看全部 ({savedDestinationsCount})
              </Link>
            )}
          </div>
          {savedDestinations.length > 0 ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {savedDestinations.map((destination) => (
                <Link
                  key={destination.id}
                  href={`/destinations/${destination.id}`}
                  className="block bg-gray-700 rounded-lg p-4 hover:bg-gray-600 transition"
                >
                  {destination.imageUrl && (
                    <div className="relative h-32 mb-4">
                      <img
                        src={destination.imageUrl}
                        alt={destination.name}
                        className="w-full h-full object-cover rounded"
                      />
                    </div>
                  )}
                  <h3 className="font-semibold text-white">{destination.name}</h3>
                  <p className="text-gray-300 text-sm mt-2">
                    {destination.description || '暂无描述'}
                  </p>
                </Link>
              ))}
            </div>
          ) : (
            <p className="text-gray-400">还没有收藏任何目的地</p>
          )}
        </div>

        {/* 收藏的行程部分 */}
        <div className="border-t border-gray-700 p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-semibold text-white">收藏的行程</h2>
            {savedTripsCount > 6 && (
              <Link
                href="/saved-trips"
                className="text-blue-400 hover:text-blue-300 text-sm"
              >
                查看全部 ({savedTripsCount})
              </Link>
            )}
          </div>
          {savedTrips.length > 0 ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {savedTrips.map((trip) => (
                <Link
                  key={trip.id}
                  href={`/trips/${trip.id}`}
                  className="block bg-gray-700 rounded-lg p-4 hover:bg-gray-600 transition"
                >
                  <h3 className="font-semibold text-white">{trip.title}</h3>
                  <p className="text-gray-300 text-sm mt-2">
                    {trip.description || '暂无描述'}
                  </p>
                  <div className="mt-4 flex items-center text-sm text-gray-400">
                    <span>{trip._count.activities} 个活动</span>
                    <span className="mx-2">•</span>
                    <span>{trip._count.savedBy} 人收藏</span>
                  </div>
                </Link>
              ))}
            </div>
          ) : (
            <p className="text-gray-400">还没有收藏任何行程</p>
          )}
        </div>
      </div>
    </div>
  );
} 